<template>
  <div>
    <el-form class="lable-top" label-position="top" size="mini">
      <el-row v-permission="['super']" :gutter="10">
        <el-col :span="4">
          <el-form-item label="组织">
            <el-select v-model="search.org_id" filterable>
              <el-option
                v-for="(item, index) in company"
                :key="index"
                :label="item.name"
                popper-class="w100"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label=" ">
            <el-button @click="handleClick">查询用户</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="el-row--flex is-justify-space-between">
      <div class="el-row--flex">
        <el-button size="small" @click="handleButtonCommend('UserDelete')">
          用户删除
        </el-button>
        <el-button
          size="small"
          @click="handleButtonCommend('UserChangePassword')"
        >
          修改密码
        </el-button>
        <el-button size="small" @click="handleButtonCommend('UserSetName')">
          设置名称
        </el-button>
        <el-button size="small" @click="handleButtonCommend('OTPEnable')"
          >OTP 启用</el-button
        >
        <el-button
          size="small"
          style="margin-left: 0;"
          @click="handleButtonCommend('OTPDisable')"
        >
          OTP 禁用
        </el-button>
        <el-button size="small" @click="handleButtonCommend('UserUnDisable')"
          >用户启用</el-button
        >
        <el-button
          size="small"
          style="margin-left: 0;"
          @click="handleButtonCommend('UserDisable')"
        >
          用户禁用
        </el-button>
        <el-button size="small" @click="handleButtonCommend('UserSetOrg')">
          设置组织管理员
        </el-button>
        <el-button
          size="small"
          style="margin-left: 0;"
          @click="handleButtonCommend('UserUnSetOrg')"
        >
          取消组织管理员
        </el-button>
        <div class="pl10">
          <el-button
            v-permission="['super']"
            size="small"
            @click="handleButtonCommend('UserSetSuper')"
          >
            设置超级管理员
          </el-button>
          <el-button
            size="small"
            style="margin-left: 0;"
            @click="handleButtonCommend('UserUnSetSuper')"
          >
            取消超级管理员
          </el-button>
        </div>
      </div>
      <div>
        <el-button size="small" @click="$refs.NewUser.show()">
          创建新用户
        </el-button>
      </div>
    </div>

    <el-table
      class="mt10"
      :data="tableData"
      :header-cell-style="{ background: '#f5f5f5' }"
      size="mini"
    >
      <el-table-column label="选择" width="60">
        <template slot-scope="scope">
          <el-radio
            v-model="tableSelect"
            :label="scope.row.id"
            style="margin-left: 10px;"
            @change="getTemplateRow(scope.row.id)"
          >
            &nbsp;
          </el-radio>
        </template>
      </el-table-column>
      <el-table-column label="用户 ID" prop="id" sortable />
      <el-table-column label="姓名" prop="last_name" sortable>
        <template slot-scope="scope">
          <div>{{ scope.row.last_name }} {{ scope.row.first_name }}</div>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" prop="email" />
      <el-table-column label="创建时间" prop="create_time" sortable />
      <el-table-column label="角色" prop="role" sortable />
      <el-table-column label="OTP" prop="otp_status" sortable />
      <el-table-column label="状态">
        <template slot-scope="scope">
          <div
            :class="[
              'status',
              scope.row.status === '可用' ? 'success' : 'fail'
            ]"
          ></div>
        </template>
      </el-table-column>
    </el-table>

    <div class="mt10 el-row--flex is-justify-end">
      <el-pagination
        background
        :current-page="page"
        layout="total, prev, pager, next"
        :page-size="limit"
        :page-sizes="[100, 200, 300, 400]"
        small
        :total="count"
        @current-change="handleCurrentChangePage"
      />
    </div>
    <new-user ref="NewUser" @change="loadingUserList" />
    <change-password ref="ChangePassword" />
  </div>
</template>

<script>
import org_getall from "@/utils/mixin/org_getall";
import NewUser from "@/views/organization/toast/newUser";
import radioTable from "@/utils/mixin/radioTable";
import checkSelectTable from "@/utils/mixin/checkSelectTable";
import org from "@/api/org";
import user from "@/api/user";
import ChangePassword from "@/views/organization/toast/changePassword";
export default {
  name: "User",
  components: { ChangePassword, NewUser },
  mixins: [org_getall, radioTable, checkSelectTable],
  data: () => {
    return {
      search: {
        org_id: ""
      },
      tableData: [],
      limit: 20,
      page: 1,
      count: 0
    };
  },
  mounted() {
    this.loadingData();
  },
  methods: {
    handleUserChangePassword({ id }) {
      this.$refs.ChangePassword.show(id);
    },
    handleUserSetSuper({ id }) {
      user.setsuper({ user_id: id }).then(res => {
        this.$message.success(res.data.message);
        this.loadingUserList();
      });
    },
    handleUserUnSetSuper({ id }) {
      user.unsetsuper({ user_id: id }).then(res => {
        this.$message.success(res.data.message);
        this.loadingUserList();
      });
    },
    handleUserUnSetOrg({ id }) {
      user
        .unsetorg({
          user_id: id
        })
        .then(res => {
          this.$message.success(res.data.message);
          this.loadingUserList();
        });
    },
    handleUserSetOrg({ id }) {
      user
        .setorg({
          user_id: id
        })
        .then(res => {
          this.$message.success(res.data.message);
          this.loadingUserList();
        });
    },
    handleUserDisable({ id }) {
      user
        .disable({
          user_id: id
        })
        .then(res => {
          this.$message.success(res.data.message);
          this.loadingUserList();
        });
    },
    handleUserUnDisable({ id }) {
      user
        .undisable({
          user_id: id
        })
        .then(res => {
          this.$message.success(res.data.message);
          this.loadingUserList();
        });
    },
    handleOTPDisable({ id }) {
      user
        .otp_disable({
          user_id: id
        })
        .then(res => {
          this.$message.success(res.data.message);
          this.loadingUserList();
        });
    },
    handleOTPEnable({ id }) {
      user
        .otp_enable({
          user_id: id
        })
        .then(res => {
          this.$alert(
            "目标用户 OTP 认证启用成功！请通过 FreeOTP 或 Microsoft Authenticator 扫描二维码完成令牌创建。<br />" +
              '<img style="width: 100%; height: 100%; object-fit: contain;" src="data:image/png;base64,' +
              res.data.img +
              '" />' +
              "<br />预共享密钥：<br / ><strong>" +
              res.data.secret +
              "</strong><br /><br /><br />请将该密钥以安全的方式告知目标用户，<br />该密钥仅在此处出现一次，务必妥善保管。 <br />若不慎遗失，请重新启用。",
            res.data.message,
            {
              dangerouslyUseHTMLString: true
            }
          );
          this.loadingUserList();
        });
    },
    handleUserSetName({ id }) {
      this.$prompt("请输入名称", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(({ value }) => {
          let user_last_name = value.charAt(0);
          let user_first_name = value.substr(1, value.length - 1);

          return user.setname({
            user_id: id,
            user_last_name,
            user_first_name
          });
        })
        .then(res => {
          this.$message.success(res.data.message);
          this.loadingUserList();
        });
    },

    handleUserDelete({ id }) {
      user
        ._delete({
          user_id: id
        })
        .then(res => {
          this.$message.success(res.data.message);
          this.loadingUserList();
        });
    },
    handleButtonCommend(module) {
      let data = {};
      this.is_check_table("id") &&
        (data = this.is_get_select_data()) &&
        this[`handle${module}`](data);
    },

    handleCurrentChangePage(val) {
      this.page = val;
      this.loadingUserList();
    },

    async loadingData() {
      await this.loadingOrgGetall();
      await this.loadingUserList();
    },

    loadingUserList() {
      return org
        .org_users({
          org_id: this.search.org_id,
          limit: this.limit,
          page: this.page
        })
        .then(res => {
          this.count = res.data.count;
          this.tableData = res.data.users;
        });
    },
    handleClick() {
      this.page = 1;
      this.loadingUserList();
    },
    setName() {
      this.$prompt("请输入名称", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(({}) => {})
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入"
          });
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.status {
  width: 15px;
  height: 15px;
  border-radius: 100px;
}
.success {
  background-color: $--color-success;
}
.fail {
  background-color: $--color-danger;
}
</style>
